/**
 * 承包方设置 列表页
 *
 * 作者 admin
 * 日期 2024-07-29 14:19:02
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-baseContractor'),
        $query = $view.find('#query'),
        $add = $view.find('#add'),
        $contractorTeamAdd = $view.find('#contractorTeamAdd'),
        $searchForm = $view.find('#baseContractor-table-form'),
        leftTableIns,
        rightTableIns;


    form.verify(validate);
    form.render();
    $contractorTeamAdd.attr("disabled",true).addClass("layui-btn-disabled");

    initTable();

    let contractorTeamTableQueryParams = {
        tenantId:null,
        contractorId:null,
        contractorName:null,
        teamName:null,
        status:null
    } ;

    function initTable() {
        initLeftTable();
    }

    function initLeftTable(){
        //初始化承包商表格
        leftTableIns = febs.table.init({
            elem: $view.find('table[name="baseContractorTable"]'),
            id: 'baseContractorTable',
            url: ctx + 'baseContractor/list',
            where: getQueryParams(),
            height: getTableHeight(),
            skin: '',
            cols: [[
                {type: 'numbers', title: '序号', width: 60 ,fixed:'left'},
                {field: 'contractorCode', title: '承包方编号', width: 140,align: 'center'},
                {field: 'contractorName', title: '承包方名称', minWidth: 120,event:'detail',templet:function (d) {
                        return '<p style="color:#01aaed;cursor:pointer">'+d.contractorName+'</p>'
                    }},
                {field: 'contacts', title: '联系人', width: 115,align: 'center'},
                {field: 'contactsPhone', title: '联系方式', width: 115,align: 'center'},
                {field: 'status', title: '状态', align:'center',toolbar: '#status-bar' , width: 100  },
                {title: '操作', toolbar: '#baseContractor-option',align:'center', width: 215,fixed: 'right'}
            ]],
            toolbar: '#baseContractor-toolbar',
            defaultToolbar: [],
            done: function (res, curr, count) {
                if(res && res.count > 0 ){
                    $view.find(".layui-table-view[lay-table-id='baseContractorTable'] .layui-table-body.layui-table-main tr[data-index=0] button[lay-event='set']").click();
                }else{
                    initRightTable()
                    $view.find('#contractorTeamAdd').attr("disabled",true).addClass("layui-btn-disabled");
                }
            }
        });
    }

    function initRightTable(){
        //初始话承包队表
        rightTableIns = febs.table.init({
            elem: $view.find('table[name="baseContractorTeamTable"]'),
            id: 'baseContractorTeamTable',
            url: ctx + 'baseContractorTeam/listByContractorId',
            where: contractorTeamTableQueryParams,
            skin: '',
            height: getTableHeight(),
            cols: [[
                {type: 'numbers', title: '序号', minWidth: 40 ,fixed:'left'},
                {field: 'teamName', title: '承包队名称', minWidth: 160 ,event:'detail',templet:function (d) {
                        return '<p style="color:#01aaed;cursor:pointer">'+d.teamName+'</p>'
                    }},
                {field: 'constructionDept', title: '实施部门', width: 140 ,align:'center'},
                {field: 'teamUsersName', title: '人员明细', minWidth: 120,templet:function (d){
                        let returnText = ""
                        $.each(d.teamUserList,function (index,item){
                            if("1" == item.status){
                                returnText += `<button class="layui-btn layui-btn-xs layui-btn-success" >${item.uname}</button>`
                            }else{
                                returnText += `<button class="layui-btn layui-btn-xs layui-btn-disabled" disabled>${item.uname}</button>`
                            }
                        })
                        if(commonJS.isEmpty(returnText)){
                            returnText = "--"
                        }
                        return returnText;
                    }
                },
                {field: 'status', title: '状态', align:'center',toolbar: '#status-bar1' , width: 100  },
                {title: '操作', toolbar: '#baseContractorTeam-option',align:'center', width: 160,fixed: 'right'}
            ]],
            toolbar: '#baseContractorTeam-toolbar',
            defaultToolbar: [],
        });
    }

    table.on('sort(baseContractorTable)', function (obj) {
        leftTableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    table.on('toolbar(baseContractorTable)', function (obj) {
        if (obj.event === 'add') {
            febs.modal.open('新增承包方', 'baseContractor/add', {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '90%' :  ['900px','500px'],
                yes: function (index, layero) {
                    $('#baseContractor-edit').find('#submit').trigger('click');
                },
                data: {
                    tenantId: $searchForm.find('select[name="tenantId"]').val()
                }
            });
        }
    });

    table.on('toolbar(baseContractorTeamTable)', function (obj) {
        if (obj.event === 'contractorTeamAdd') {
            if(!commonJS.isEmpty(contractorTeamTableQueryParams.contractorId)){
                // contractorTeamTableQueryParams.contractorId = $view.find('input[name="clauseNo"]').val()
                //重载右侧承包队表
                initRightTable();
            }else {
                febs.alert.error('未选中承包队。');
                return;
            }
            febs.modal.open('新增承包队', 'baseContractorTeam/add', {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '95%' : ['900px','480px'],
                yes: function (index, layero) {
                    $('#baseContractorTeam-edit').find('#submit').trigger('click');
                },
                data: {
                    tenantId: $searchForm.find('select[name="tenantId"]').val(),
                    tenantName: $searchForm.find('select[name="tenantId"]').find('option:selected').text().trim(),
                    contractorId: contractorTeamTableQueryParams.contractorId,
                    contractorName: contractorTeamTableQueryParams.contractorName

                }
            });
        }
        if (obj.event === 'teamQuery') {
            queryContractorTeam()
        }
    });

    $query.on('click', function () {
        //重载左侧表格
        leftTableIns.reload({where: getQueryParams(), page: {curr: 1}});
    });



    table.on('tool(baseContractorTable)', function (obj) {
        //表格编辑删除事件
        var contractorId = obj.data.contractorId;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            febs.modal.open('修改承包方', 'baseContractor/update/'+contractorId, {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '90%' :  ['900px','500px'],
                yes: function (index, layero) {
                    $('#baseContractor-edit').find('#submit').trigger('click');
                },
            });
        } else if (layEvent === 'del') {
            febs.modal.confirm('删除岗位', '确定删除所选承包方？', function () {
                deleteContractorByIds(contractorId);
            });
        } else if (layEvent === 'detail') {
            febs.modal.open('承包方详细', 'baseContractor/detail/'+contractorId, {
                btn: ['取消'],
                area: $(window).width() <= 750 ? '90%' :  ['900px','500px'],
                yes: function (index, layero) {
                    layer.close(index)
                },
            });
        }else if (layEvent === 'set') {
            contractorTeamTableQueryParams.tenantId =obj.data.tenantId
            contractorTeamTableQueryParams.contractorId = obj.data.contractorId
            contractorTeamTableQueryParams.contractorName = obj.data.contractorName
            contractorTeamTableQueryParams.teamName  = $view.find('input[name="teamName"]').val();
            contractorTeamTableQueryParams.status  =  $view.find("select[name='teamStatus']").find("option:selected").val();
            initRightTable();
        }
    });


    table.on('checkbox(baseContractorTable)', function (obj) {
        //勾选框事件，有勾选则展示新增承包队按钮，无勾选则禁用
        if(table.checkStatus('baseContractorTable').data.length == 0){
            $contractorTeamAdd.attr("disabled",true).addClass("layui-btn-disabled");
        }else {
            $contractorTeamAdd.attr("disabled",false).removeClass("layui-btn-disabled");
        }

    });


    function getQueryParams() {
        return {
            contractorName: $searchForm.find('input[name="contractorName"]').val(),
            tenantId: $searchForm.find("select[name='tenantId']").find("option:selected").val(),
            status: $searchForm.find("select[name='status']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };
    }

    function deleteContractorByIds(ids) {
        febs.get(ctx + 'baseContractor/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        })
    }



    table.on('tool(baseContractorTeamTable)', function (obj) {
        //承包队表格编辑删除事件
        var contractorTeamId = obj.data.contractorTeamId;
        var teamName = obj.data.teamName;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            febs.modal.open('修改承包队', 'baseContractorTeam/update/'+contractorTeamId, {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '95%' :  ['900px','480px'],
                yes: function (index, layero) {
                    $('#baseContractorTeam-edit').find('#submit').trigger('click');
                },
            });
        } else if (layEvent === 'del') {
            febs.modal.confirm('删除承包队', '确定删除所选承包队？', function () {
                deleteContractorTeamByIds(contractorTeamId);
                $query.trigger('click');
            });

        } else if(obj.event === 'detail'){
            febs.modal.open('承包队详情', 'baseContractorTeam/detail/'+contractorTeamId, {
                area: $(window).width() <= 750 ? '95%' : ['900px','750px'],
                btn: ['取消'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.close(index);
                },
            });
        }
    });


    function deleteContractorTeamByIds(contractorTeamId) {
        //根据承包队Id 删除承包队
        febs.get(ctx + 'baseContractorTeam/delete/' + contractorTeamId, null, function () {
            febs.alert.success('删除数据成功');
            // $query.trigger('click');
        })
    }


    form.on('switch(teamStatus)', function (obj) {
        //岗位状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其 postId
        var id =  table.cache['baseContractorTable'][index].contractorId;
        console.log("承包商Id"+id);
        febs.modal.confirm('更改承包方状态', '确认更改承包方状态',function (){
            updateContractorStatus(id,status);
        },function (){
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function updateContractorStatus(postId,status) {
        //更新岗位状态
        let model={
            contractorId : postId,
            status : status
        }
        febs.post(ctx + 'baseContractor/updateContractorStatus', model, function () {
            febs.alert.success('修改承包方状态成功');
        })
    }

    form.on('switch(teamUserStatus)', function (obj) {
        //岗位状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其 postId
        var id =  table.cache['baseContractorTeamTable'][index].contractorTeamId;
        console.log("承包队Id"+id);
        febs.modal.confirm('更改承包队状态', '确认更承包队状态',function (){
            updateContractorTeamStatus(id,status);
        },function (){
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function updateContractorTeamStatus(id,status) {
        //更新岗位状态
        let model={
            contractorTeamId : id,
            status : status
        }
        febs.post(ctx + 'baseContractorTeam/updateContractorTeamStatus', model, function () {
            febs.alert.success('修改承包队状态成功');
        })
    }

    function  queryContractorTeam (obj){
        if(!commonJS.isEmpty(contractorTeamTableQueryParams.contractorId)){
            contractorTeamTableQueryParams.teamName = $view.find('input[name="teamName"]').val();
            contractorTeamTableQueryParams.status = $view.find("select[name='teamStatus']").find("option:selected").val();
            //重载右侧承包队表
            initRightTable();
        }else {
            febs.alert.error('未选中条款类型。');

        }
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        leftTableIns.reload({height: getTableHeight()});
        // rightTableIns.reload({height: getTableHeight()});
    });
});